package level.editor.menu;

import java.awt.Component;
import java.awt.HeadlessException;
import java.io.File;

import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;

import core.Constants;

import level.editor.command.Command;
import level.editor.command.RequiresModule;
import level.editor.command.RequiresUpdate;
import level.editor.mediator.Module;
import level.editor.state.StateModule;
import level.state.StateWriter;

/*
 * Command implementation of save function. Init will extract directory/savename
 * data from StateModule, and execute will an XML write function to save state
 * data.
 */

public class StateSaveAsCommand extends Command implements RequiresUpdate,
		RequiresModule
{
	public StateSaveAsCommand()
	{
		super("StateModule");
	}

	public void execute(Module m)
	{
		StateModule module = (StateModule) m;
		String dir = Constants.DEFAULT_SAVE_DIR;
		String fileName = "*.xml";
		if (module.getState().getFile() != null)
		{
			dir = module.getState().getFile().getParent();
			fileName = module.getState().getFile().getName();
		}
		FileFilter filter = new FileNameExtensionFilter("XML Files (*.xml)",
				"xml");
		JFileChooser fc = new JFileChooser(dir)
		{
			public File getSelectedFile()
			{
				File selectedFile = super.getSelectedFile();

				if (selectedFile != null)
				{
					String name = selectedFile.getName();
					if (!name.endsWith(".xml"))
					{
						selectedFile = new File(selectedFile.getParentFile(),
								name + ".xml");
					}
				}
				return selectedFile;
			}

			protected JDialog createDialog(Component parent)
					throws HeadlessException
			{
				JDialog dlg = super.createDialog(parent);
				dlg.setLocation(20 + dlg.getLocation().x,
						20 + dlg.getLocation().y);
				return dlg;
			}

			public void approveSelection()
			{
				if (getDialogType() == SAVE_DIALOG)
				{
					File selectedFile = getSelectedFile();
					if ((selectedFile != null) && selectedFile.exists())
					{
						int response = JOptionPane
								.showConfirmDialog(
										this,
										"The file "
												+ selectedFile.getName()
												+ " already exists. Do you want to replace the existing file?",
										"Ovewrite file",
										JOptionPane.YES_NO_OPTION,
										JOptionPane.WARNING_MESSAGE);
						if (response != JOptionPane.YES_OPTION)
							return;
					}
				}
				super.approveSelection();
			}
		};

		fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
		fc.setFileFilter(filter);
		fc.setSelectedFile(new File(fileName));
		int returnVal = fc.showSaveDialog(module.getWindow());
		if (returnVal != JFileChooser.APPROVE_OPTION)
			return;

		module.getState().setFile(fc.getSelectedFile());
		module.setModified(false);
		StateWriter.write(module.getState());
	}

}
